package com.wing.common.constant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.util.StringUtil;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SapUtils {

    /**
     * 获取SAP接口的soap报文
     *
     * @param dataList
     * @param fileList
     * @return
     */
    private static String getSAPXml(String dataList, String fileList) {
        String soaoXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wor=\"http://workflow.webservices.tool.westvalley.com\">\n" +
                "   <soapenv:Header/>" +
                "   <soapenv:Body>" +
                "      <wor:ToolCabinetpersonnelInformation>" +
                "      <wor:in0>" +
                dataList + fileList +
                "      </wor:in0>" +
                "      </wor:ToolCabinetpersonnelInformation>" +
                "   </soapenv:Body>" +
                "</soapenv:Envelope>";
        return soaoXML;
    }

    /**
     * 发送post请求
     * @param url 服务器地址
     * @param userName 账号
     * @param password 密码
     * @param body xml报文体
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    private static String sendHttpPost(String url, String userName, String password, String body) throws IOException, URISyntaxException {
        String UTF8 = "UTF-8";
        URI serverURI = new URI(url);
        // 身份认证
        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(
                new AuthScope(serverURI.getHost(), serverURI.getPort()),
                new UsernamePasswordCredentials(userName, password));
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credProvider).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(new StringEntity(body, UTF8));
        // 发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        // 获取请求结果
        String responseContent = EntityUtils.toString(entity, UTF8);
        response.close();
        httpClient.close();
        return responseContent;
    }


    /**
     * xml格式化，消除转义字符
     *
     * @param inputXML
     * @return
     * @throws Exception
     */
    private static String formatXml(String inputXML) throws Exception {
        String xml = null;
        SAXReader reader = new SAXReader();
        XMLWriter writer = null;
        Document document = reader.read(new StringReader(inputXML));
        try {
            if (document != null) {
                StringWriter stringWriter = new StringWriter();
                OutputFormat format = OutputFormat.createPrettyPrint();
                writer = new XMLWriter(stringWriter, format);
                // 取消转义
                writer.setEscapeText(false);
                writer.write(document);
                writer.flush();
                xml = stringWriter.getBuffer().toString();
            }
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return xml;
    }

    /**
     * 发送SAP报文
     * @param url
     * @param userName
     * @param password
     * @param dataXml
     * @param fileXml
     * @return
     * @throws Exception
     */
    public static String send(String url, String userName, String password,String dataXml, String fileXml) throws Exception {
        //封装请求体
        String xmlRequest = getSAPXml(dataXml, fileXml);
        // 格式化
        String xmlRequest2 = formatXml(xmlRequest);
        System.out.println("【SAP报文】>>>>:{}:"+ xmlRequest2);
        //获取请求结果
        String xmlRequestFormat = sendHttpPost(url, userName, password, xmlRequest2);
        System.out.println("【SAP报文】返回结果>>>>:{}:"+ xmlRequestFormat);
        //xml格式化
        String result = formatXml(xmlRequestFormat);
        return result;
    }

    /**
     * 发送请求, 且获取返回结果
     * 测试方法
     *
     * @return
     */
    public String execImpexpPaymentService() {
        String url = "http://tkoa.tkmold.com/services/doInvoiceInfo";
        String resultText = "";
        try {
            //SapData data = new SapData();
            //data.setErrorMonth("2022-01");
            //data.setBukrs("1");
            //String dataStr = JaxbUtil.convertToXml(data);
            //SapFile file = new SapFile();
            //file.setErrorMonth("2022-01");
            //String fileStr = JaxbUtil.convertToXml(file);
            //log.info("【测试】接口调用>>>>:arg0:{}，arg1:{}", dataStr, fileStr);
            //封装请求体
            String xmlRquest = getSAPXml("", "");
            String xmlRquest2 = formatXml(xmlRquest);
            //获取请求结果
            String xmlRquestFormat = sendHttpPost(url, "WSUSER", "WSPASS", xmlRquest2);
            //xml格式化
            String result = formatXml(xmlRquestFormat);
             resultText = subString(result,"<ns1:out>", "</ns1:out>");
            System.out.println("【测试】接口结果>>>>result:{}:"+ resultText);
            JSONArray jsonArray = JSON.parseArray(resultText);
            /*for(int i = 0; i < jsonArray.size(); i++){
                JSONObject jsonObj = jsonArray.getJSONObject(i);
                String departmentName = jsonObj.getString("departmentname");
                String jobtitlename = jsonObj.getString("jobtitlename");
                System.out.println("部门：" + departmentName + "---岗位："+jobtitlename);
            }*/

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultText;
    }

    public static void main(String[] args) {
        SapUtils httpUtil = new SapUtils();
        httpUtil.execImpexpPaymentService();
    }

    /**
     * 截取字符串string中特定字符str1、str2之间的字符串
     * @param string
     * @param str1
     * @param str2
     * @return 截取之后的字符串result（不包含str1和str2,只取中间的字符串）
     */
    public static String subString(String string, String str1, String str2){
        //记录特定字符str1、str2索引
        int beginIndex = string.indexOf(str1);
        int endIndex = string.indexOf(str2);
        //索引<0，表示字符串中不存在字符，return
        if(beginIndex < 0){
            return "[" + string + "]" + " 中不存在 " + str1 + "，无法截取";
        } else if(endIndex < 0){
            return "[" + string + "]" + " 中不存在 " + str2 + "，无法截取";
        }
        //参数str1 str2位置可调换，不管str1 str2在字符串中的位置顺序如何，都能截取它们之间的字符串
        if(beginIndex > endIndex){
            int tempIndex = beginIndex;
            beginIndex = endIndex;
            endIndex = tempIndex;
            String tempStr = str1;
            str1 = str2;
            str2 = tempStr;
        }
        //截取 第一个substring()方法包含边界字符str1或str2,为了使截取结果不包含边界，用第二个substring()方法去掉边界字符
        String result = string.substring(beginIndex, endIndex).substring(str1.length());
        return result;
    }
}
